﻿using Microsoft.Extensions.Configuration;
using System.Text;
using System.Text.Json;

namespace Api.Shared.Utils.MyClient
{
    public class MyHttpClient
    {
        private readonly string apiUrl;
        private readonly HttpClient client;

        //public MyHttpClient(string apiUrl, HttpClient client)
        //{
        //    this.apiUrl = apiUrl;
        //    this.client = client;
        //}

        /// <summary>
        /// 工厂+key
        /// </summary>
        /// <param name="clientFactory">client工厂</param>
        /// <param name="key">appsettings中的key</param>
        public MyHttpClient(HttpClient client, string key)
        {
            this.client = client;

            IConfigurationRoot? buider = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
            apiUrl = buider[key]!;
        }

        private JsonSerializerOptions options =
            new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, };

        public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
        {
            var requestMessage = new HttpRequestMessage(
                baseRequest.Method?? HttpMethod.Get,
                apiUrl + baseRequest.Route
            );

            if (baseRequest.Parameter != null)
            {
                var jsonParameter = JsonSerializer.Serialize(baseRequest.Parameter, options);
                var content = new StringContent(
                    jsonParameter,
                    Encoding.UTF8,
                    baseRequest.ContentType
                );
                requestMessage.Content = content;
            }

            var response = await client.SendAsync(requestMessage);
            var contentString = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                var rep = JsonSerializer.Deserialize<ApiResponse>(contentString, options);
                return rep ?? new() { Status = true, Message = "序列化成功,但是内容为空" };
            }
            else
            {
                return new ApiResponse()
                {
                    Status = false,
                    Result = null,
                    Message = response.ReasonPhrase
                };
            }
        }

        public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
            where T : class, new()
        {
            var requestMessage = new HttpRequestMessage(
                baseRequest.Method!,
                apiUrl + baseRequest.Route
            );

            if (baseRequest.Parameter != null)
            {
                var jsonParameter = JsonSerializer.Serialize(baseRequest.Parameter, options);
                var content = new StringContent(
                    jsonParameter,
                    Encoding.UTF8,
                    baseRequest.ContentType
                );
                requestMessage.Content = content;
            }

            var response = await client.SendAsync(requestMessage);
            var contentString = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                var result = JsonSerializer.Deserialize<ApiResponse<T>>(contentString, options);
                return result ?? new ApiResponse<T>() { Status = false, Message = "反序列化结果为null" };
            }
            else
            {
                return new ApiResponse<T>() { Status = false, Message = response.ReasonPhrase };
            }
        }
    }
}
